<?php

namespace App\Clients;

use App\Imports\RedBookClueImport;
use App\Models\RedBookAccount;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;

class RedBookClient extends BaseClient
{
    public $account;

    /**
     * @param $account
     */
    public function __construct($account)
    {
        $this->account = $account;
    }

    public function login()
    {
        $proxy = env('HELPER_PROXY' ,'');
        $response = $this->post('https://customer.xiaohongshu.com/api/cas/loginWithAccount', [
            "proxy" => $proxy,
            'headers' => [
                'authority' => 'customer.xiaohongshu.com',
                'sec-ch-ua' => '"Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"',
                'sec-ch-ua-mobile' => '?0',
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31',
                'content-type' => 'application/json;charset=UTF-8',
                'accept' => 'application/json, text/plain, */*',
                'sec-ch-ua-platform' => '"macOS"',
                'origin' => 'https://ad.xiaohongshu.com',
                'sec-fetch-site' => 'same-site',
                'sec-fetch-mode' => 'cors',
                'sec-fetch-dest' => 'empty',
                'referer' => 'https://ad.xiaohongshu.com/',
                'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            ],
            'json' => [
                "account" => $this->account['username'],
                "password" => $this->account['password'],
                "service" => "https://ad.xiaohongshu.com"
            ]
        ]);

        $body = $response->getBody()->getContents();
        Log::info('debug red book: > login', [
            'body' => $body,
            'account' => $this->account,
        ]);
        $json = json_decode($body, true);
        if ($token = data_get($json, 'data')) {
            $sessionResponse = $this->post('https://ad.xiaohongshu.com/api/leona/session', [
                'json' => [
                    "clientId" => "https://ad.xiaohongshu.com",
                    "ticket" => $token
                ],
                'headers' => [
                    'authority' => 'ad.xiaohongshu.com',
                    'sec-ch-ua' => '"Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"',
                    'x-t' => '1672623931095',
                    'x-b3-traceid' => '92e4a044fa4db670',
                    'sec-ch-ua-mobile' => '?0',
                    'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31',
                    'content-type' => 'application/json;charset=UTF-8',
                    'accept' => 'application/json, text/plain, */*',
                    'x-s' => 's21W0jcp0jVv1BMLsB5bZjA+sgqJZgVksBsb1BACZBA3',
                    'sec-ch-ua-platform' => '"macOS"',
                    'origin' => 'https://ad.xiaohongshu.com',
                    'sec-fetch-site' => 'same-origin',
                    'sec-fetch-mode' => 'cors',
                    'sec-fetch-dest' => 'empty',
                    'referer' => 'https://ad.xiaohongshu.com/',
                    'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                ]
            ]);
            $sessionBody = $sessionResponse->getBody()->getContents();
            Log::info('debug red book: > $sessionBody', [
                'body' => $sessionBody,
            ]);
            return preg_match("/成功/", $sessionBody);
        }
        return false;
    }

    public function pageList()
    {
        $response = $this->get('https://ad.xiaohongshu.com/api/leona/landing_page/page?page=1&pageSize=500', [
            'headers' => [
                'authority' => 'ad.xiaohongshu.com',
                'sec-ch-ua' => '"Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"',
                'sec-ch-ua-mobile' => '?0',
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31',
                'accept' => 'application/json, text/plain, */*',
                'sec-ch-ua-platform' => '"macOS"',
                'sec-fetch-site' => 'same-origin',
                'sec-fetch-mode' => 'cors',
                'sec-fetch-dest' => 'empty',
                'referer' => 'https://ad.xiaohongshu.com/aurora/ad/tools/landingPage',
                'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            ]
        ]);
        $body = $response->getBody()->getContents();
        $json = json_decode($body, true);
        $list = data_get($json, 'data.list');
        return collect($list)->pluck('id');
    }

    public function generateTake($ids, $startDate, $endDate)
    {
        $response = $this->post('https://ad.xiaohongshu.com/api/leona/landingpage_batch_download/commit', [
            'headers' => [
                'authority' => 'ad.xiaohongshu.com',
                'sec-ch-ua' => '"Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"',
                'sec-ch-ua-mobile' => '?0',
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31',
                'content-type' => 'application/json;charset=UTF-8',
                'accept' => 'application/json, text/plain, */*',
                'sec-ch-ua-platform' => '"macOS"',
                'origin' => 'https://ad.xiaohongshu.com',
                'sec-fetch-site' => 'same-origin',
                'sec-fetch-mode' => 'cors',
                'sec-fetch-dest' => 'empty',
                'referer' => 'https://ad.xiaohongshu.com/aurora/ad/tools/landingPage',
                'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            ],
            'json' => [
                'input' => [
                    'extra' => [
                        'page_ids' => $ids,
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                    ]
                ]
            ]
        ]);

        $body = $response->getBody()->getContents();
        $json = json_decode($body, true);
        return data_get($json, 'data.task_id');
    }

    public function takeStatus($takeId)
    {
        $response = $this->get("https://ad.xiaohongshu.com/api/leona/landingpage_batch_download/task/status?task_id=$takeId", [
            'headers' => [
                'authority' => 'ad.xiaohongshu.com',
                'sec-ch-ua' => '"Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"',
                'sec-ch-ua-mobile' => '?0',
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31',
                'accept' => 'application/json, text/plain, */*',
                'sec-ch-ua-platform' => '"macOS"',
                'sec-fetch-site' => 'same-origin',
                'sec-fetch-mode' => 'cors',
                'sec-fetch-dest' => 'empty',
                'referer' => 'https://ad.xiaohongshu.com/aurora/ad/tools/landingPage',
                'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            ],
        ]);
        $body = $response->getBody()->getContents();
        Log::info('debug red book: >takeStatus', [
            'body' => $body,
        ]);
        $json = json_decode($body, true);
        return data_get($json, 'data.status');
    }

    public function tryTakeStatus($takeId, $tires = 10)
    {
        $count = 0;
        do {
            sleep(5);
            $result = $this->takeStatus($takeId) === 'FINISHED';
            $count++;
        } while ((!$result && $count <= $tires));

        return $result;
    }

    public function getTakeFileUrl($takeId)
    {
        $response = $this->get("https://ad.xiaohongshu.com/api/leona/landingpage_batch_download/task/result?task_id=$takeId", [
            'headers' => [
                'authority' => 'ad.xiaohongshu.com',
                'sec-ch-ua' => '"Chromium";v="94", "Microsoft Edge";v="94", ";Not A Brand";v="99"',
                'sec-ch-ua-mobile' => '?0',
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31',
                'accept' => 'application/json, text/plain, */*',
                'sec-ch-ua-platform' => '"macOS"',
                'sec-fetch-site' => 'same-origin',
                'sec-fetch-mode' => 'cors',
                'sec-fetch-dest' => 'empty',
                'referer' => 'https://ad.xiaohongshu.com/aurora/ad/tools/landingPage',
                'accept-language' => 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            ],
        ]);
        $body = $response->getBody()->getContents();
        Log::info('debug red book: > getTakeFileUrl', [
            'body' => $body,
        ]);
        $json = json_decode($body, true);
        return data_get($json, 'data.result.file_url');
    }

    public function getExcelClue($startDate, $endDate)
    {
        if (!$this->login())
            return false;
        $ids = $this->pageList();
        $takeId = $this->generateTake($ids->toArray(), $startDate, $endDate);
        if ($this->tryTakeStatus($takeId)) {
            $path = $this->getTakeFileUrl($takeId);
            if ($path) {
                $filename = Str::uuid();
                $filename = "{$filename}.xlsx";
                Storage::disk('local')->put($filename, file_get_contents($path));
                $path = Storage::disk('local')->path($filename);
                Excel::import(new RedBookClueImport(), $path);
                return true;

            }
        }
        return false;
    }




}
